package com.zhang.yygh.hosp.controller.api;

import com.atguigu.yygh.model.hosp.HospitalSet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhang.yygh.common.exception.YYGHException;
import com.zhang.yygh.common.result.R;
import com.zhang.yygh.hosp.service.HospitalService;
import com.zhang.yygh.hosp.service.HospitalSetService;
import com.zhang.yygh.hosp.utils.HttpRequestHelper;
import com.zhang.yygh.hosp.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@RequestMapping("/api/hosp")
@RestController
public class ApiHospitalController {

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private HospitalSetService hospitalSetService;

    @PostMapping("/hospital/show")
    public R getHospitalInfo(HttpServletRequest httpServletRequest){
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(httpServletRequest.getParameterMap());
        //TODO:校验
        String hoscode = (String) paramMap.get("hoscode");
        Map<String,Object> map=hospitalService.getHospitalByHoscode(hoscode);
        return R.ok().code(200).data(map);

    }

    @PostMapping("saveHospital")
     public R saveHospital(HttpServletRequest httpServletRequest){
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(httpServletRequest.getParameterMap());
        String sign = (String) paramMap.get("sign");
        //响应码应该是200
        String hoscode = (String) paramMap.get("hoscode");
        QueryWrapper<HospitalSet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hoscode",hoscode);
        HospitalSet one = hospitalSetService.getOne(queryWrapper);
        if (one==null){
            throw new YYGHException(20001,"没有该医院信息");
        }
        String encrypt = MD5.encrypt(one.getSignKey());
        if (!StringUtils.isEmpty(encrypt)&&!StringUtils.isEmpty(sign)&&sign.equals(encrypt)){
            String logoData = (String) paramMap.get("logoData");
            logoData=logoData.replaceAll(" ","+");
            paramMap.put("logoData",logoData);
            hospitalService.saveHospital(paramMap);
        }else {
            throw new YYGHException(20001,"校验失败");
        }

        return R.ok().code(200);
     }
}
